import 'package:animated_digit/animated_digit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_integral/address_write_alert.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_utils.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/online_pay_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/vip_support_model.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/widgets/privilege_item.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/widgets/vip_sub_widget.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_alert.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_entry_widget.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

//会员中心
class MineVIPSubPage extends StatefulWidget {
  final VipSupportModel model;
  const MineVIPSubPage(this.model, {super.key});

  @override
  State<MineVIPSubPage> createState() => _MineVIPSubPageState();
}

class _MineVIPSubPageState extends State<MineVIPSubPage> {
  /// 所有会员卡
  final dataSource = <VipProductModel>[];
  VipProductModel? currentVipProduct;
  VipProductModel? preSaleProduct;
  VipProductModel? upgradeProdcut;
  List<NewPrivilege> allPrivileges = []; //所有的会员权益

  VipProductListModel? productModel; //会员卡组
  VipProductListModel? preSaleProductModel; //预售卡组

  AnimatedDigitController controller = AnimatedDigitController(0);

  @override
  void initState() {
    super.initState();
    dataSource.clear();
    // 预售卡和普通会员卡数据区分
    widget.model.list?.forEach((element) {
      if (element.position == '会员卡') {
        productModel = element;
      }
      if (element.position == '预售卡') {
        preSaleProductModel = element;
        preSaleProduct = element.list?.firstOrNull;
      }
    });
    //优先添加预售卡
    if (preSaleProductModel != null &&
        (preSaleProductModel?.list ?? []).isNotEmpty &&
        PreSaleProvider().advanceStatus?.activityStatus == true &&
        !PreSaleProvider().isPayAll()) {
      dataSource.add(preSaleProductModel!.list!.first..isPreSale = true);
      currentVipProduct = dataSource.first;
    }
    dataSource.addAll(productModel?.list ?? []);
    if (currentVipProduct == null) currentVipProduct = productModel?.list?.first;
    allPrivileges = currentVipProduct?.newPrivilege ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 18.w),
      child: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  12.sizeBoxH,
                  Consumer<GlobalStore>(
                    builder: (_, provider, __) => _buildUserInfo(provider),
                  ),
                  18.sizeBoxH,
                  0.5.line,
                  18.sizeBoxH,
                  _buildVipTips(),
                  27.sizeBoxH,
                  _buildVipItems(), //会员选项
                  20.sizeBoxH,
                  0.5.line,
                  //预售入口
                  if (preSaleProduct != null) ...[
                    20.sizeBoxH,
                    PreSaleVipEntryWidget(),
                    20.sizeBoxH,
                  ],
                  VipPrivilegeView(model: currentVipProduct), //会员权益
                  _buildIntegralExchangeView(), //积分兑换商品
                  92.sizeBoxH,
                ],
              ),
            ),
          ),
          _buildPayBtn(), //支付按钮
        ],
      ),
    );
  }

  _buildUserInfo(GlobalStore provider) {
    return Row(
      children: [
        NetworkImageLoader(
          imageUrl: provider.meInfo?.portrait ?? '',
          width: 68,
          height: 68,
          borderRadius: 34,
        ),
        14.sizeBoxW,
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '${provider.meInfo?.name ?? ''}',
                style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
              ),
              Text(
                provider.vipTime(),
                style: TextStyle(color: Color(0xff999999), fontSize: 12, fontWeight: FontWeight.w400),
              ),
            ],
          ),
        )
      ],
    );
  }

  _buildVipTips() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          '开通VIP享受会员特权',
          style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
        ),
        Text(
          '早买早享受',
          style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
        ),
      ],
    );
  }

  _buildVipItems() {
    return Container(
      height: 140,
      child: ListView.separated(
        separatorBuilder: (_, __) => 6.sizeBoxW,
        itemCount: dataSource.length,
        clipBehavior: Clip.none,
        scrollDirection: Axis.horizontal,
        itemBuilder: (BuildContext context, int index) {
          final model = dataSource[index];
          final select = currentVipProduct?.productID == model.productID;
          return SizedBox(
            width: 111,
            height: double.infinity,
            child: VIPProductItem(
              model,
              isSelect: select,
              onTap: () {
                currentVipProduct = model;
                setState(() {});
              },
            ),
          );
        },
      ),
    );
  }

  _buildIntegralExchangeView() {
    return Column(
      children: [
        Row(
          children: [
            Text(
              '积分兑换VIP',
              style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
            ),
            Spacer(),
            Consumer<GlobalStore>(
              builder: (_, store, __) => Text(
                '当前积分${store.wallet?.integral ?? 0}',
                style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w400),
              ),
            ),
          ],
        ),
        Container(
          height: 160,
          child: ListView.separated(
              separatorBuilder: (context, index) => SizedBox(width: 10),
              shrinkWrap: true,
              padding: EdgeInsets.only(right: 10, top: 12),
              scrollDirection: Axis.horizontal,
              itemCount: widget.model.integralList?.length ?? 0,
              itemBuilder: (BuildContext context, int index) {
                return _buildExchangeProductItem(widget.model.integralList?[index]);
              }),
        ),
      ],
    );
  }

  //兑换产品Item
  Widget _buildExchangeProductItem(IntegralList? item) {
    return Column(
      children: [
        Container(
          width: 111,
          height: 100,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(8)),
            border: Border.all(width: 1),
            gradient: LinearGradient(begin: Alignment(0.85, 0.15), end: Alignment(0.88, 0.93), colors: [
              const Color(0xffFFEEDC),
              const Color(0xffEEC7B2),
            ]),
          ),
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            Text(
              "${item?.name ?? ''}",
              style: const TextStyle(
                color: const Color(0xff421A11),
                fontWeight: FontWeight.w500,
                fontSize: 14.0,
              ),
            ),
            4.sizeBoxH,
            Text(
              "${item?.price ?? 0}积分",
              style: const TextStyle(
                color: const Color(0xff763E2D),
                fontWeight: FontWeight.w500,
                fontSize: 18.0,
              ),
            ),
          ]),
        ),
        12.sizeBoxH,
        GestureDetector(
          onTap: () => onExchange(item),
          child: Container(
            width: 72,
            height: 28,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(20)),
              color: const Color(0xff1F2031),
            ),
            child: Center(
              child: // 兑换
                  Text(
                "兑换",
                style: TextStyle(
                  color: Color(0xffffffff).withOpacity(.9),
                  fontSize: 12.0,
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  _buildPayBtn() {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        mainAxisSize: MainAxisSize.min,
        children: [
          GestureDetector(
            onTap: () => payAction.call(),
            child: Consumer<PreSaleProvider>(
              builder: (context, provider, child) {
                if (currentVipProduct?.isPreSale ?? false) {
                  return PreSaleActivityButton(
                    onTap: () => payAction.call(),
                  );
                } else
                  return Container(
                    height: 48.h,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: AppColors.actionRed,
                      borderRadius: BorderRadius.circular(3),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      _priceTitle(),
                      style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
                    ),
                  );
              },
            ),
          ),
          12.sizeBoxH,
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('支付问题反馈，点击联系 ', style: textStyle(12, Color(0xffBFBFC1), FontWeight.w400)),
              GestureDetector(
                onTap: () => MineUtils.goCSPage(),
                child: Text('在线客服', style: textStyle(12, AppColors.primaryHighColor, FontWeight.w400)),
              )
            ],
          ),
          16.sizeBoxH,
        ],
      ),
    );
  }

  payAction() {
    if (currentVipProduct?.isPreSale ?? false) {
      PreSaleProvider().onInitiatePayAction(currentVipProduct!);
      return;
    }
    if (currentVipProduct?.rchgTypeUI.isEmpty ?? true) {
      showToast("未配置支付方式，请联系客服");
      return;
    }
    Get.bottomSheet(
      OnlinePayPage(vipProductModel: currentVipProduct),
      isScrollControlled: true,
    );
  }

  //积分兑换
  onExchange(IntegralList? model) async {
    final hasIntegral = globalStore.wallet?.integral ?? 0;

    if (hasIntegral < (model?.price ?? 0)) {
      showToast('积分不足，无法兑换～');
      return;
    }
    if (model?.type == 5) {
      AddressWriteAlert.show(Get.context!, model?.id ?? '');
      return;
    }
    final res = await MineService.integralExchangeSomething(model?.id ?? '');
    if (res) {
      showToast('兑换成功～');
      globalStore.refreshWallet();
    }
  }

  String _priceTitle() {
    if (currentVipProduct?.isPreSale == true) return PreSaleProvider().generatePayButtonTitle();
    return '¥${(currentVipProduct?.discountedPrice ?? 0) ~/ 10}/立即支付';
  }
}

class MinePrivilegeSubPage extends StatefulWidget {
  final VipSupportModel model;
  const MinePrivilegeSubPage(this.model, {super.key});

  @override
  State<MinePrivilegeSubPage> createState() => _MinePrivilegeSubPageState();
}

class _MinePrivilegeSubPageState extends State<MinePrivilegeSubPage> {
  final dataSource = [];
  @override
  void initState() {
    super.initState();
    widget.model.list?.forEach((element) {
      if (element.position == '特权卡') {
        dataSource.addAll(element.list ?? []);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (dataSource.isEmpty) return CErrorWidget();
    return ListView.separated(
      itemCount: dataSource.length,
      padding: EdgeInsets.only(left: 18.w, right: 18.w, top: 14),
      separatorBuilder: (BuildContext context, int index) {
        return 14.sizeBoxH;
      },
      itemBuilder: (BuildContext context, int index) {
        final model = dataSource[index];
        return PrivilegeItem(
          dataSource[index],
          onTap: () {
            if (model.rchgTypeUI.isEmpty) {
              showToast("未配置支付方式，请联系客服");
              return;
            }
            Get.bottomSheet(
              OnlinePayPage(vipProductModel: model),
              isScrollControlled: true,
            );
          },
        );
      },
    );
  }
}
